package com.eyaomall.wxmanage.common.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lycheeframework.core.model.IDataObject;

/**
 * 将内容并写入实体
 * @author zhangjl
 *
 */
public class SetEntityValue {
	
	private static final Logger LOG = LoggerFactory.getLogger(SetEntityValue.class);
	
	public static IDataObject setEntityValue(IDataObject dataObject, IDataObject newDataObject){
		if (dataObject == null || newDataObject==null) return null;
		
		Field[] fields = dataObject.getClass().getDeclaredFields();
		
		try {
			Map<Object, Object> map = new HashMap<Object,Object>();
			for(int i=0; i<fields.length; i++) {
				Field field = fields[i];
				
				field.setAccessible(true);
				
				if ("serialVersionUID".equals(field.getName())) continue;
				
				if (field.get(dataObject) != null) {
					map.put(field.getName(), field.get(dataObject));
				} 
			}
			
			Field[] newFields = newDataObject.getClass().getDeclaredFields();
			for(int i=0; i<fields.length; i++) {
				Field field = newFields[i];
				field.setAccessible(true);
				if(map.get(field.getName())!=null){
					if(field.get(newDataObject)==null)
						field.set(newDataObject,map.get(field.getName()));
				}
			}
			
			return newDataObject;
			
		} catch (Exception e) {
			LOG.error(e.getMessage(),e);
			return null;
		}
	}  
}
